package extras;

import java.io.IOException;
import java.sql.Timestamp;
import webService.AccesoWebService;
import com.androidmodule.onthego.R;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import activities.ActivityDialogoBroadCast;
import activities.ActivityPromocionHot;
import activities.ActivityPromocionesHot;
import activities.MainActivity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;

public class BroadCastWifiConected extends BroadcastReceiver{
	static final int NOTIFICAR_RED_VALIDA = 1;
	static  final int NOTIFICAR_PROMOCIONES_VIGENTES=2;
	final Uri defaultNotificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

	@Override
	public void onReceive(Context contextoParametro, Intent intentoParametro) {
        
		Bundle extras = intentoParametro.getExtras();
		String action = intentoParametro.getAction();
		NetworkInfo conexion = (NetworkInfo) extras
                .getParcelable(ConnectivityManager.EXTRA_NETWORK_INFO);
	    if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
	    	if (conexion.getType() == ConnectivityManager.TYPE_WIFI) {
                if (conexion.getState().name()
                                .equals(NetworkInfo.State.CONNECTED.name())) {
                	
                	hiloValidarRed hiloValidarCentro = new hiloValidarRed(contextoParametro);
                    hiloValidarCentro.execute();              
                } else if (conexion.getState().name()
                                .equals(NetworkInfo.State.DISCONNECTED.name())) {
                        //Codigo a ejecutar cuando nos desconectamos de una red Wiffi
                	leerPreferencias.writeConexionValida(contextoParametro, false);
                }
            }
	    	if (conexion.getType() == ConnectivityManager.TYPE_MOBILE) {
	    		 if (conexion.getState().name()
                         .equals(NetworkInfo.State.CONNECTED.name())) {
	    			 leerPreferencias.writeConexionValida(contextoParametro, false);
	    		 }
	    	}    
	    }
	}
	
	public void notificarCentroAsociado(Context parametroContexto){
		NotificationCompat.Builder notBuilder =
		        new NotificationCompat.Builder(parametroContexto)
		        .setSmallIcon( R.drawable.hot_prom_notification)
		        .setContentTitle(parametroContexto.getString(R.string.app_name))
		        .setAutoCancel(true)
		        .setSound(Uri.parse(leerPreferencias.readTonoNotificacion(parametroContexto)))
		        .setContentText(parametroContexto.getString(R.string.notificacion_centro_asociado));
		Intent resultIntent = new Intent(parametroContexto, MainActivity.class);
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(parametroContexto);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addNextIntentWithParentStack(resultIntent);
		// Adds the Intent that starts the Activity to the top of the stack
		//stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
		        stackBuilder.getPendingIntent(
		            0,
		            PendingIntent.FLAG_UPDATE_CURRENT
		        );
		notBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotificationManager =
			    (NotificationManager) parametroContexto.getSystemService(Context.NOTIFICATION_SERVICE);
			// mId allows you to update the notification later on.
			mNotificationManager.notify(NOTIFICAR_RED_VALIDA, notBuilder.build());
	}
	public void notificarPromocionesVigentes(Context parametroContexto){
		NotificationCompat.Builder notBuilder =
		        new NotificationCompat.Builder(parametroContexto)
		        .setSmallIcon(R.drawable.hot_prom_notification)
		        .setContentTitle(parametroContexto.getString(R.string.app_name))
		        .setAutoCancel(true)
		        .setSound(Uri.parse(leerPreferencias.readTonoNotificacion(parametroContexto)))
		        .setContentText(parametroContexto.getString(R.string.notificacion_promocion_hot));
		Intent resultIntent = new Intent(parametroContexto, ActivityPromocionesHot.class);
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(parametroContexto);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addNextIntentWithParentStack(resultIntent);
		// Adds the Intent that starts the Activity to the top of the stack
		//stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
		        stackBuilder.getPendingIntent(
		            0,
		            PendingIntent.FLAG_UPDATE_CURRENT
		        );
		notBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotificationManager =
			    (NotificationManager) parametroContexto.getSystemService(Context.NOTIFICATION_SERVICE);
			// mId allows you to update the notification later on.
			mNotificationManager.notify(NOTIFICAR_PROMOCIONES_VIGENTES, notBuilder.build());
	}

	/**
	 * Este hilo se encarga de ejcutar lso metodos contra el web service el servdior
	 * valdiar centro comercial, registrar usuario en el gcm y en el mismo servidor
	 * @author Marco
	 *
	 */
	public class hiloValidarRed extends AsyncTask<Void, Integer, String[]> {
        int codigoError =AccesoWebService.NO_ERROR;
        String[] resultado = new String[2];
        Context contexto;
        NetInfo infoRed;
        
        public hiloValidarRed(Context parametroContexto){
            contexto = parametroContexto;
            infoRed= new NetInfo(contexto);
        }

        @Override
        protected String[] doInBackground(Void... params) { 
            try{
    	        AccesoWebService accesoWeb = new AccesoWebService();
    	        resultado = accesoWeb.validarCentroComercial(infoRed.getBSSID());
            }
            catch (java.net.SocketTimeoutException timeOut){
           	    codigoError = AccesoWebService.TIMEOUT_ERROR;
           	    timeOut.printStackTrace();
            }
            catch (Exception e){
            	e.printStackTrace();
            	codigoError=666;
            }
          
            return resultado;
        }

        protected void onProgressUpdate(Integer... values){}
        
        protected void onPostExecute(String[] validacion){
            if(codigoError!=AccesoWebService.NO_ERROR){
            	Intent intent = new Intent(contexto,ActivityDialogoBroadCast.class);
            	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            	contexto.startActivity(intent);
            }    
            else{
            	 if (validacion[0].equals("true"))	{
                	  if(leerPreferencias.readNoticarCentroAsociado(contexto)){
                          notificarCentroAsociado(contexto);
                      }
                	  leerPreferencias.writeConexionValida(contexto, true);
                	  // si es true y estoy en una red deun centro valido, me registro
                      /////////GCM2/////////////////
                  	  regid = getRegistrationId(contexto);

                      if (regid.length() == 0) {
                          registerBackground(contexto);
                      }
                      else{
                    	  registrarUsuarioEnServidor(contexto, regid);
                      }
                      gcm = GoogleCloudMessaging.getInstance(contexto);
                      ///////////////////GCM2///////////
                	  
                	  if(validacion[1].equalsIgnoreCase("true")){
                          if(leerPreferencias.readNotificarPromocionHot(contexto))
                		      notificarPromocionesVigentes(contexto);
                	  }
                  }
            }
        }               	      
	}
	//////////////////////////////////PRUEBAGCM2//////////////////////////////////////////////

    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
            "onServerExpirationTimeMs";
    String regid;
    /**
     * Default lifespan (7 days) of a reservation until it is considered expired.
     */
    public static final long REGISTRATION_EXPIRY_TIME_MS = 1000 * 3600 * 24 * 7;

    /**
     * Substitute you own sender ID here.
     */
    String SENDER_ID = "798215255224";
    /**
     * Tag used on log messages.
     */
    static final String TAG = "GCMDemo";
    GoogleCloudMessaging gcm;
    
    /**
     * Gets the current registration id for application on GCM service.
     * <p>
     * If result is empty, the registration has failed.
     *
     * @return registration id, or empty string if the registration is not
     *         complete.
     */
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.length() == 0) {
            Log.v(TAG, "Registration not found.");
            return "";
        }
        // check if app was updated; if so, it must clear registration id to
        // avoid a race condition if GCM sends a message
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion || isRegistrationExpired(context)) {
            Log.v(TAG, "App version changed or registration expired.");
            return "";
        }
        return registrationId;
    }
    
    /**
     * @return Application's {@code SharedPreferences}.
     */
    private SharedPreferences getGCMPreferences(Context context) {
        return context.getSharedPreferences(MainActivity.class.getSimpleName(), 
                Context.MODE_PRIVATE);  
    }
    
    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }
    /**
     * Checks if the registration has expired.
     *
     * <p>To avoid the scenario where the device sends the registration to the
     * server but the server loses it, the app developer may choose to re-register
     * after REGISTRATION_EXPIRY_TIME_MS.
     *
     * @return true if the registration has expired.
     */
    private boolean isRegistrationExpired(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        // checks if the information is not stale
        long expirationTime =
                prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
        return System.currentTimeMillis() > expirationTime;
    }
    
    /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration id, app versionCode, and expiration time in the 
     * application's shared preferences.
     */
    private void registerBackground(final Context context) {
    	new AsyncTask<Void, Integer, String>() {
        String msg="";

            @Override
            protected String doInBackground(Void... params) { 
            	 msg = "";
                 try {
                     if (gcm == null) {
                         gcm = GoogleCloudMessaging.getInstance(context);
                     }
                     regid = gcm.register(SENDER_ID);
                     msg = "Device registered, registration id=" + regid;

                     // You should send the registration ID to your server over HTTP,
                     // so it can use GCM/HTTP or CCS to send messages to your app.

                     // For this demo: we don't need to send it because the device
                     // will send upstream messages to a server that echo back the message
                     // using the 'from' address in the message.

                     // Save the regid - no need to register again.
                     setRegistrationId(context, regid);
                     registrarUsuarioEnServidor(context, regid);
                 } catch (IOException ex) {
                     msg = "Error :" + ex.getMessage();
                 }
                 return msg;
            }

            protected void onProgressUpdate(Integer... values){}
            
            protected void onPostExecute(String[] validacion){
            	 Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
            }             
    }.execute();
    }
    /**
     * Stores the registration id, app versionCode, and expiration time in the
     * application's {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration id
     */
    private void setRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.v(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        long expirationTime = System.currentTimeMillis() + REGISTRATION_EXPIRY_TIME_MS;

        Log.v(TAG, "Setting registration expiry time to " +
                new Timestamp(expirationTime));
        editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
        editor.commit();
    }
    
    public void registrarUsuarioEnServidor(final Context contexto, final String GcmRegistrationID){
    	new AsyncTask<Void, Integer, String>() {
            String msg="";
            int codigoError = AccesoWebService.NO_ERROR;

                @Override
                protected String doInBackground(Void... params) { 
                	 String msg = "";
                	 AccesoWebService webService = new AccesoWebService();
                	 NetInfo infoMovil = new NetInfo(contexto);
                	 msg= "Usuario registrado en Servidor";
                     try {
                         webService.registrarGCM(infoMovil.getMac(), infoMovil.getBSSID(),GcmRegistrationID);
                     }
                     catch(java.net.SocketTimeoutException timeOut){
                    	 codigoError = AccesoWebService.TIMEOUT_ERROR;
                     }
                     catch (IOException ex) {
                         msg = "Error :" + ex.getMessage();
                     }
                     return msg;
                }

                protected void onProgressUpdate(Integer... values){}

                protected void onPostExecute(String mensaje){
                	if(codigoError!=AccesoWebService.NO_ERROR){
                		//Intent intent = new Intent(contexto,ActivityDialogoBroadCast.class);
                    	//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    	//contexto.startActivity(intent);
                	}
                	else{
                		Toast.makeText(contexto, mensaje, Toast.LENGTH_LONG).show();
                	}
                	
                	
                	
                }
        }.execute();
    }
}
